import { VuexModule, Module, Action, getModule, Mutation } from 'vuex-module-decorators'
import { IDO_CONTRACT, IDOAbi } from '@/contract'
import { ethers } from "ethers";
import { toWei } from '@/utils/format'


import store from '@/store'

export interface IDOState {
}

@Module({ dynamic: true, store, name: 'IDO', namespaced: true })
class IDO extends VuexModule implements IDOState {

    @Action({ rawError: true })
    public userInfo(address = store.getters.userAddr): Promise<any> {
        const contract = new store.getters.web3.eth.Contract(IDOAbi, IDO_CONTRACT);
        return contract.methods.userInfo(address).call()
    }

    @Action({ rawError: true })
    public contractInfo(): Promise<any> {
        const contract = new store.getters.web3.eth.Contract(IDOAbi, IDO_CONTRACT);
        return contract.methods.contractInfo().call()
    }


    @Action({ rawError: true })
    public async idoUSDT(amount: string | number): Promise<any> {
        const ethersProvider = new ethers.providers.Web3Provider(
            window.ethereum,
            "any"
        );
        const contract = new ethers.Contract(
            IDO_CONTRACT,
            IDOAbi,
            ethersProvider.getSigner()
        );
        const result = await contract.idoUSDT(
            store.getters.referrer || store.getters.userAddr,
            toWei(amount)
        );
        return result.wait()
    }

    @Action({ rawError: true })
    public async getERC20(): Promise<any> {
        const ethersProvider = new ethers.providers.Web3Provider(
            window.ethereum,
            "any"
        );
        const contract = new ethers.Contract(
            IDO_CONTRACT,
            IDOAbi,
            ethersProvider.getSigner()
        );
        const result = await contract.getERC20();
        return result.wait()
    }

}

export const IDOModule = getModule(IDO)